<template>
  <div>
    <h1>生词本</h1>


    <!-- 显示单词列表 -->
    <div>
      <h2>单词列表</h2>
      <ul>
        <li v-for="word in words" :key="word.id">
          {{ word.word }} - {{ word.definition }} - {{ word.chineseDefinition }} - {{ word.phonetic }}
<!--          <button @click="deleteWord(index)">删除</button>-->
          <button @click="deleteWord(index)" >
            <font-awesome-icon :icon="['fas', 'trash']" />
          </button>
<!--          <button @click="" >-->
<!--            <font-awesome-icon :icon="['fas', 'edit']" />-->
<!--          </button>-->
        </li>
      </ul>
    </div>

    <!-- 添加新单词 -->
    <div>
      <h2>添加新单词</h2>
      <form @submit.prevent="addNewWord">
        <ul>
          <label for="new-word">单词:</label>
          <input type="text" id="new-word" v-model="newWord.word" required/>
        </ul>
        <ul>
          <label for="new-definition">释义:</label>
          <input type="text" id="new-definition" v-model="newWord.definition" required/>
        </ul>
        <ul>
          <label for="new-chinese-definition">中文:</label>
          <input type="text" id="new-chinese-definition" v-model="newWord.chineseDefinition" required/>
        </ul>
        <ul>
          <label for="new-phonetic">发音:</label>
          <input type="text" id="new-phonetic" v-model="newWord.phonetic" required/>
        </ul>
<!--        <button type="button" @click="lookupWord">查词</button>-->
        <button @click="lookupWord" >
          <font-awesome-icon :icon="['fas', 'search']" />
        </button>
        <button type="submit" >
          <font-awesome-icon :icon="['fas', 'add']" />
        </button>
<!--        <button type="submit">添加</button>-->
      </form>
    </div>

    <!-- 保存单词列表为文件 -->
    <div>
      <h2>保存生词本</h2>
      <label for="filename-input">文件名:</label>
      <input type="text" id="filename-input" v-model="filename" placeholder="请输入文件名" required />
<!--      <button @click="saveWordsAsCsv">保存生词奥</button>-->
      <button @click="saveWordsAsCsv" >
        <font-awesome-icon :icon="['fas', 'save']" />
      </button>
    </div>
  </div>
</template>

<script>
import {mapGetters, mapActions} from 'vuex';
import axios from 'axios'; // 假设您使用了 axios 库来发送 HTTP 请求

export default {
  name: 'CustomWordBookView',
  computed: {
    ...mapGetters(['getWords']),
    words() {
      return this.localWords;
    }
  },
  methods: {
    ...mapActions(['addWord']),
    addNewWord() {
      // 将新单词添加到本地列表
      this.localWords.push({...this.newWord, id: Date.now()});

      // 调用 Vuex 动作将新单词添加到全局状态
      this.addWord(this.newWord);

      // 清空表单
      this.newWord = {
        word: '',
        definition: '',
        chineseDefinition: '',
        phonetic: ''
      };
    },
    deleteWord(index) {
      // 从 localWords 数组中删除指定索引的单词
      this.localWords.splice(index, 1);
    },
    saveWordsAsCsv() {
      if (this.filename) {
      const csvContent = "data:text/csv;charset=utf-8," + this.wordsToCsvString();
      const encodedUri = encodeURI(csvContent);
      const link = document.createElement("a");
      link.setAttribute("href", encodedUri);
      link.setAttribute("download", `${this.filename}.csv`);
      document.body.appendChild(link); // Required for FF
      link.click();
      document.body.removeChild(link);
      } else {
        alert('请输入文件名');
      }
    },
    wordsToCsvString() {
      const headers = ['word', 'definition', 'chineseDefinition', 'phonetic'];
      const rows = [headers.join(',')];

      this.localWords.forEach(word => {
        const row = [
          word.word,
          word.definition,
          word.chineseDefinition,
          word.phonetic
        ].map(value => `${value.replace(/"/g, '')}`).join(',');
        rows.push(row);
      });

      return rows.join('\n');
    },
    async lookupWord() {
      if (this.newWord.word) {
        try {
          const API_URL = 'https://api.dictionaryapi.dev/api/v2/entries/en/';

          try {
            //console.log('Fetching word details for:', newWord);
            const response = await axios.get(`${API_URL}${this.newWord.word}`);
            const details = response.data;
            console.log(details);
            const phonetics = details[0].phonetics;
            const phonetic = phonetics.find(p => p.text)?.text || '';
            this.newWord.phonetic = phonetic;

            const meanings = details[0].meanings;
            const definition = meanings[0]?.definitions[0]?.definition || '';
            this.newWord.definition = definition;

            this.newWord.chineseDefinition = '';

            // const { definition, chineseDefinition, phonetic } = response.data;
            // this.newWord.definition = definition || '';
            // this.newWord.chineseDefinition = chineseDefinition || '';
            // this.newWord.phonetic = phonetic || '';

            return true; // 返回成功标志
          } catch (error) {
            console.error('Failed to fetch word details:', error);
            // 可以在这里添加更多的错误处理逻辑
            return false; // 返回失败标志
          }

          // 更新表单中的数据

        } catch (error) {
          console.error('查词失败:', error);
          alert('查词失败，请检查单词是否正确或稍后再试。');
        }
      } else {
        alert('请输入单词');
      }
    }
  },
  data() {
    return {
      newWord: {
        word: '',
        definition: '',
        chineseDefinition: '',
        phonetic: ''
      },
      localWords: [] // 本地单词列表
    };
  },
  created() {
    // 初始化本地单词列表
   // this.localWords = this.getWords.map(word => ({...word, id: Date.now()}));
  }
};
</script>